import requests,os
from bs4 import BeautifulSoup as bs

def getpage():
	'''
	根据url和请求头爬取购物车信息
	购物车商品已选择两个 分别为：
	百草味夏威夷果
	联想游戏本
	'''
	url='https://cart.jd.com/cart.action'

	headers={
		'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
		'Accept-Encoding':'gzip, deflate, br',
		'Accept-Language':'zh-CN,zh;q=0.9',
		'Cache-Control':'max-age=0',
		'Connection':'keep-alive',
		'Cookie':'3AB9D23F7A4B3C9B=VFJRMZUITFP7ENKAS2PZMWJWWTAWWBLMP2D6JPZUMG7BP3FTYEHBHBM6IMBYUZ6B4OKRJOPJ3RP2R2OVMR34WRSREM; __jdu=706448601; mba_muid=706448601; shshshfpa=e7669337-f6a8-c2ad-c0cc-9cd1fe682ea8-1525955791; shshshfpb=176f62e0734dc4b11be4528c28259e6748158b5510010ca605af43cca9; _jrda=3; intlIpLbsCountrySite=jd; intlIpLbsCountryIp=211.97.3.148; _jdzt=zt_jt; __jdc=122270672; PCSYCityID=1601; unpl=V2_bzNtbUpXExBwCBZQch8IDWIARQlKVBZHIAxEAHgZXQZjBxMPclRCFXwUR1NnGVQUZwcZXUtcRhVFCEdkeR5eA24zGlpLX0odG1p2VH8aVAdvABReQFFKHUULRmRzKVoEYAYXVEVWQyVFD3ZkIEwyAm5WElVEUBAUIg9CVkseWQNnARRaQWdCJXQ4DTp6VFoEYAYXVEVWQyV0OEU%3d; CCC_SE=ADC_osq%2b9qlUz8e4SkkFzTO0bGWr1BCooQDcVdlv04CKQxOJtJ7pU00kidfKGWxXsc4Oy4R%2bYhl0SHnWluSegd3fwmhnQXx15jNEYtnqXBznSczL5g1Gcj%2b5QEsvFL8GH2g2Bl85J8be1kn%2bSzR%2fSLSmj9NQLTjOdq%2bX7fxI8Fi87ncg1bzQyT%2fMM9Kc1w0Pc5dPTa4Y1ShzW1QYyloaVZNCk94BsPnA7TXz%2f%2bwzjpOghI9W2yUZZgHrW6%2fjhIdQS22Mld%2fKVX4Lc5hve6SEZkwtnVPGRgPESUdx8S8pfRKTbyLajTUnXux9ZNb9TzEJGr6nVMhylgTikimksYLMk7uUlSApSZcP6FUfgpaOOIa%2ff7%2f%2fzDDbqIdQFBxNWpXY2%2bQrWEMADzhyBlr4EITJRZEV%2fHaA%2bUaF9c5r5AIXG3SvZ1ExA3hiVwF3a9ncOR9oaZUFcwMIf78APCWDILwJger4LbfS00lrc0Sisevf1IhQdCZx70cDXcSY85nzHMg%2fpS6cXTBn5AIyxCbXjq70XQeQKRreYl7JKSuUwFsTqmiC1Busz1zfFfGYd4AA0YhK3xI7fjpfyXj8%2baTDo3qWavinHE0SPbmt4zGgKkzwsbs43HYsUXiB9L9%2bHwed67z3PmT5Eub8Dl%2fOJzne2qQ7mlrUGw%3d%3d; __jdv=122270672|p.egou.com|t_36378_968989_c|tuiguang|91a441a587e942fe92dcd53e2102550c|1529392725136; user-key=0d68867f-7a33-4494-bd65-f5802322bab0; cd=0; __jda=122270672.706448601.1518880420.1529392725.1529406236.42; shshshfp=b60a8067c44a19f6b5240c88287b7e60; cart-main=xx; mt_xid=V2_52007VwUTVVhdW10eSSlUBGYBR1NUUE4KGxwfQAAyBBpOVAwCXwNNGFRQNFRHBVQLU1wvShhcDHsCFU5dUENaF0IYWQ5nBSJQbVhiWRxNH10NbgMQYl1eWlM%3D; ipLoc-djd=1-72-2819; cn=3; shshshsID=8801e227dd98f0c99e29955e5b2e68ba_6_1529406283626; __jdb=122270672.3.706448601|42.1529406236',	
		'Host':'cart.jd.com',
		'Upgrade-Insecure-Requests':'1',
		'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.5478.400 QQBrowser/10.1.1550.400',
	}

	try:
		res = requests.get(url,headers=headers)
		if res.status_code==200:
			return res.text
		else:
			return None
	except Exception as err:
		print("爬取失败，原因是："+str(err))
		return None

def parsepage(content):
	'''解析html，获取商品的商品名、颜色、价格、单价、数量、总价、小结等信息'''
	if content:
		soup=bs(content,'lxml')
		items = soup.find_all(name="div",attrs={"product":"1"})
		for item in items:
			yield {
				'title':item.find(name="div",attrs={'class':'p-name'}).a.get_text().strip(),
				'color':item.find(name="div",attrs={'class':'props-txt'}).string.strip(),
				'price':item.find(name="div",attrs={'class':'cell p-price p-price-new '}).strong.string,
				'quantity':item.find(name="input",attrs={'autocomplete':'off'}).attrs['value'],
				'total':item.find(name="div",attrs={'class':'cell p-sum'}).strong.string,
				'all':soup.find(name="span",attrs={"class":"price sumPrice"}).em.get_text()
			}

def showpage(content,no):
	'''打印购物车信息'''
	if content:
		print("第"+str(no)+"件商品信息")
		print("名称："+content['title'])
		print(content['color'])
		print("单价："+content['price'])
		print("数量："+content['quantity'])
		print("总价："+content['total'])


def main():
	html = getpage()
	items=list(parsepage(html))
	no=1
	print("当前京东购物车有"+str(len(items))+"件商品")
	for item in items:
		showpage(item,no)
		no=no+1
	print("当前购物车商品总价为："+items[0]['all']+"元")

if __name__ == '__main__':
	main()